package com.zenithmind.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.common.exception.BusinessException;
import com.zenithmind.mall.mapper.CartMapper;
import com.zenithmind.mall.mapper.ProductMapper;
import com.zenithmind.mall.pojo.dto.CartDTO;
import com.zenithmind.mall.pojo.entity.Cart;
import com.zenithmind.mall.pojo.entity.Product;
import com.zenithmind.mall.pojo.vo.CartVO;
import com.zenithmind.mall.service.CartService;
import com.zenithmind.mall.service.ProductStockService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 购物车服务实现类
 * 
 * @author ZenithMind Team
 * @since 2025-06-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    private final CartMapper cartMapper;
    private final ProductMapper productMapper;
    private final ProductStockService productStockService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addToCart(CartDTO cartDTO, String userId) {
        // 检查商品是否存在且上架
        Product product = productMapper.selectById(cartDTO.getProductId());
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        if (product.getStatus() != 1) {
            throw new BusinessException("商品已下架");
        }
        if (!productStockService.checkStock(cartDTO.getProductId(), cartDTO.getQuantity())) {
            throw new BusinessException("库存不足");
        }

        // 检查购物车中是否已存在相同商品
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, userId)
               .eq(Cart::getProductId, cartDTO.getProductId())
               .eq(StringUtils.hasText(cartDTO.getSpecificationId()), Cart::getSpecificationId, cartDTO.getSpecificationId())
               .eq(Cart::getIsDeleted, 0);

        Cart existCart = getOne(wrapper);

        if (existCart != null) {
            // 更新数量
            int newQuantity = existCart.getQuantity() + cartDTO.getQuantity();
            if (product.getStock() < newQuantity) {
                throw new BusinessException("库存不足");
            }
            existCart.setQuantity(newQuantity);
            existCart.setUpdateBy(userId);
            return updateById(existCart);
        } else {
            // 新增购物车记录
            Cart cart = new Cart();
            BeanUtils.copyProperties(cartDTO, cart);
            cart.setUserId(userId);
            cart.setPrice(product.getPrice());
            cart.setSelected(1); // 默认选中
            cart.setCreateBy(userId);
            return save(cart);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateCartQuantity(String id, Integer quantity, String userId) {
        Cart cart = getById(id);
        if (cart == null || !cart.getUserId().equals(userId)) {
            throw new BusinessException("购物车商品不存在");
        }

        // 检查库存
        Product product = productMapper.selectById(cart.getProductId());
        if (product == null || product.getStatus() != 1) {
            throw new BusinessException("商品已下架");
        }
        if (product.getStock() < quantity) {
            throw new BusinessException("库存不足");
        }

        cart.setQuantity(quantity);
        cart.setUpdateBy(userId);
        return updateById(cart);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeFromCart(String id, String userId) {
        Cart cart = getById(id);
        if (cart == null || !cart.getUserId().equals(userId)) {
            throw new BusinessException("购物车商品不存在");
        }
        return removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeFromCart(List<String> ids, String userId) {
        // 验证所有购物车商品都属于当前用户
        List<Cart> carts = listByIds(ids);
        boolean allBelongToUser = carts.stream().allMatch(cart -> cart.getUserId().equals(userId));
        if (!allBelongToUser) {
            throw new BusinessException("包含不属于当前用户的购物车商品");
        }
        return removeByIds(ids);
    }

    @Override
    public List<CartVO> getCartList(String userId) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, userId)
               .eq(Cart::getIsDeleted, 0)
               .orderByDesc(Cart::getCreateTime);

        List<Cart> carts = list(wrapper);
        return carts.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean selectCartItem(String id, Integer selected, String userId) {
        Cart cart = getById(id);
        if (cart == null || !cart.getUserId().equals(userId)) {
            throw new BusinessException("购物车商品不存在");
        }
        cart.setSelected(selected);
        cart.setUpdateBy(userId);
        return updateById(cart);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean selectAllCartItems(Integer selected, String userId) {
        LambdaUpdateWrapper<Cart> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Cart::getUserId, userId)
               .eq(Cart::getIsDeleted, 0)
               .set(Cart::getSelected, selected);
        return update(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeSelectedItems(String userId) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, userId)
               .eq(Cart::getSelected, 1)
               .eq(Cart::getIsDeleted, 0);
        return remove(wrapper);
    }

    @Override
    public Integer getCartCount(String userId) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, userId)
               .eq(Cart::getIsDeleted, 0)
               .select(Cart::getQuantity);

        List<Cart> carts = list(wrapper);
        return carts.stream().mapToInt(Cart::getQuantity).sum();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean clearCart(String userId) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, userId)
               .eq(Cart::getIsDeleted, 0);
        return remove(wrapper);
    }

    /**
     * 转换为VO
     */
    private CartVO convertToVO(Cart cart) {
        CartVO vo = new CartVO();
        BeanUtils.copyProperties(cart, vo);

        // 获取商品信息
        Product product = productMapper.selectById(cart.getProductId());
        if (product != null) {
            vo.setProductName(product.getName());
            vo.setProductImage(product.getMainImage());
            vo.setProductPrice(product.getPrice());
            vo.setProductOriginalPrice(product.getOriginalPrice());
            vo.setProductStock(product.getStock());
            vo.setProductStatus(product.getStatus());

            // 检查商品是否有效
            vo.setIsValid(product.getStatus() == 1 && product.getStock() > 0);
            if (!vo.getIsValid()) {
                if (product.getStatus() != 1) {
                    vo.setInvalidReason("商品已下架");
                } else if (product.getStock() <= 0) {
                    vo.setInvalidReason("商品缺货");
                }
            }
        } else {
            vo.setIsValid(false);
            vo.setInvalidReason("商品不存在");
        }

        // 计算小计
        vo.setTotalAmount(vo.getProductPrice().multiply(java.math.BigDecimal.valueOf(cart.getQuantity())));

        return vo;
    }
}
